#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
优化的投资建议系统 - 第八步执行模块
整合前面7步的所有分析结果，生成完整的投资方案
"""

import sys
import os
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

class OptimizedInvestmentAdvisor:
    """优化的投资建议系统 - 专为周收益目标设计"""
    
    def __init__(self):
        # 投资配置
        self.investment_config = {
            'total_capital': 50000,        # 总资金5万
            'target_stocks': 5,            # 目标股票数量
            'weekly_target_return': 0.025, # 周收益目标2.5%
            'max_single_loss': 0.03,       # 单股最大亏损3%
            'max_total_loss': 0.03,        # 总体最大亏损3%
            'rebalance_threshold': 0.05,   # 再平衡阈值5%
        }
        
        # 风险管理配置
        self.risk_config = {
            'position_sizing': 'equal_weight',  # 等权重配置
            'diversification_min': 3,           # 最少分散化股票数
            'sector_max_weight': 0.40,          # 单行业最大权重
            'correlation_limit': 0.70,          # 相关性限制
        }
        
        # 时间管理配置
        self.time_config = {
            'analysis_frequency': 'daily',     # 分析频率：每日
            'rebalance_frequency': 'weekly',   # 再平衡频率：每周
            'review_frequency': 'monthly',     # 综合评估：每月
            'trading_hours': '09:30-15:00',    # 交易时间
        }
        
    def print_header(self, title):
        """打印标题"""
        print(f"\n{'='*80}")
        print(f"📋 {title}")
        print(f"{'='*80}")
        
    def load_all_analysis_results(self):
        """加载所有分析结果"""
        try:
            results = {}
            
            # 1. 加载筛选结果
            screening_file = 'test_screening_results.csv'
            if os.path.exists(screening_file):
                results['screening'] = pd.read_csv(screening_file)
                print(f"✅ 加载筛选结果: {len(results['screening'])} 只股票")
            
            # 2. 加载技术分析结果
            technical_file = 'test_technical_results.csv'
            if os.path.exists(technical_file):
                results['technical'] = pd.read_csv(technical_file)
                print(f"✅ 加载技术分析结果: {len(results['technical'])} 只股票")
            
            # 3. 加载基本面分析结果
            fundamental_file = 'optimized_fundamental_results.csv'
            if os.path.exists(fundamental_file):
                results['fundamental'] = pd.read_csv(fundamental_file)
                print(f"✅ 加载基本面分析结果: {len(results['fundamental'])} 只股票")
            
            # 4. 加载综合排序结果
            ranking_file = 'optimized_final_ranking.csv'
            if os.path.exists(ranking_file):
                results['ranking'] = pd.read_csv(ranking_file)
                print(f"✅ 加载综合排序结果: {len(results['ranking'])} 只股票")
            
            # 5. 加载深度分析结果
            deep_analysis_file = 'optimized_deep_analysis_results.csv'
            if os.path.exists(deep_analysis_file):
                results['deep_analysis'] = pd.read_csv(deep_analysis_file)
                print(f"✅ 加载深度分析结果: {len(results['deep_analysis'])} 只股票")
            
            # 6. 加载趋势预测结果
            prediction_file = 'optimized_trend_prediction_results.csv'
            if os.path.exists(prediction_file):
                results['prediction'] = pd.read_csv(prediction_file)
                print(f"✅ 加载趋势预测结果: {len(results['prediction'])} 只股票")
            
            return results
            
        except Exception as e:
            print(f"❌ 加载分析结果失败: {e}")
            return {}
    
    def select_final_portfolio(self, results):
        """选择最终投资组合"""
        try:
            # 优先使用最新的分析结果
            if 'prediction' in results and not results['prediction'].empty:
                # 基于趋势预测结果选择
                df = results['prediction'].copy()
                
                # 按预测分数排序
                df = df.sort_values('prediction_score', ascending=False)
                
                # 选择前5只股票
                selected_stocks = df.head(self.investment_config['target_stocks']).to_dict('records')
                
                print(f"✅ 基于趋势预测结果选择投资组合: {len(selected_stocks)} 只股票")
                
            elif 'ranking' in results and not results['ranking'].empty:
                # 基于综合排序结果选择
                df = results['ranking'].copy()
                
                # 过滤通过筛选的股票
                df = df[df['pass_filter'] == True] if 'pass_filter' in df.columns else df
                
                # 按综合分数排序
                df = df.sort_values('comprehensive_score', ascending=False)
                
                # 选择前5只股票
                selected_stocks = df.head(self.investment_config['target_stocks']).to_dict('records')
                
                print(f"✅ 基于综合排序结果选择投资组合: {len(selected_stocks)} 只股票")
                
            else:
                print("❌ 没有可用的分析结果")
                return []
            
            return selected_stocks
            
        except Exception as e:
            print(f"❌ 选择投资组合失败: {e}")
            return []
    
    def calculate_position_sizing(self, selected_stocks):
        """计算仓位配置"""
        try:
            total_capital = self.investment_config['total_capital']
            
            # 等权重配置
            if self.risk_config['position_sizing'] == 'equal_weight':
                position_size = total_capital / len(selected_stocks)
                
                for stock in selected_stocks:
                    stock['allocation'] = position_size
                    stock['allocation_percentage'] = position_size / total_capital * 100
                    
                print(f"✅ 等权重配置: 每只股票分配 ¥{position_size:,.0f} ({position_size/total_capital*100:.1f}%)")
            
            # 基于分数权重配置
            elif self.risk_config['position_sizing'] == 'score_weight':
                # 获取分数字段
                score_field = 'prediction_score' if 'prediction_score' in selected_stocks[0] else 'comprehensive_score'
                
                total_score = sum(stock.get(score_field, 0) for stock in selected_stocks)
                
                for stock in selected_stocks:
                    score = stock.get(score_field, 0)
                    weight = score / total_score if total_score > 0 else 1/len(selected_stocks)
                    stock['allocation'] = total_capital * weight
                    stock['allocation_percentage'] = weight * 100
                    
                print(f"✅ 基于分数权重配置完成")
            
            return selected_stocks
            
        except Exception as e:
            print(f"❌ 计算仓位配置失败: {e}")
            return selected_stocks
    
    def generate_trading_plan(self, selected_stocks):
        """生成交易计划"""
        try:
            print("🔄 开始生成交易计划...")
            import traceback
            
            trading_plan = {
                'total_capital': self.investment_config['total_capital'],
                'target_return': self.investment_config['weekly_target_return'],
                'stocks': [],
                'risk_control': {},
                'timeline': {}
            }
            
            total_expected_return = 0
            total_risk_score = 0
            
            print(f"📊 处理 {len(selected_stocks)} 只股票...")
            
            for i, stock in enumerate(selected_stocks):
                print(f"   处理股票 {i+1}: {stock.get('stock_code', 'N/A')}")
                
                stock_plan = {
                    'code': stock.get('stock_code', stock.get('code', 'N/A')),
                    'name': stock.get('stock_name', stock.get('name', 'N/A')),
                    'allocation': stock.get('allocation', 0),
                    'allocation_percentage': stock.get('allocation_percentage', 0),
                    'current_price': stock.get('current_price', 0),
                    'target_price': stock.get('target_price', 0),
                    'stop_loss_price': stock.get('stop_loss_price', 0),
                    'take_profit_price': stock.get('take_profit_price', 0),
                    'expected_return': stock.get('weekly_return_expectation', 0),
                    'risk_level': stock.get('risk_level', '中风险'),
                    'confidence': stock.get('confidence', 0.5),
                    'operation_advice': stock.get('operation_advice', '观望'),
                    'shares_to_buy': 0,
                    'entry_strategy': '分批买入',
                    'exit_strategy': '止损止盈'
                }
                
                # 计算购买股数
                if stock_plan['current_price'] > 0:
                    stock_plan['shares_to_buy'] = int(stock_plan['allocation'] / stock_plan['current_price'] / 100) * 100
                
                # 累计预期收益和风险
                total_expected_return += stock_plan['expected_return'] * stock_plan['allocation_percentage'] / 100
                
                # 风险分数
                risk_score = 1 if stock_plan['risk_level'] == '低风险' else 2 if stock_plan['risk_level'] == '中风险' else 3
                total_risk_score += risk_score
                
                trading_plan['stocks'].append(stock_plan)
            
            print("🔄 设置风险控制参数...")
            # 风险控制参数
            trading_plan['risk_control'] = {
                'max_single_loss': self.investment_config['max_single_loss'],
                'max_total_loss': self.investment_config['max_total_loss'],
                'stop_loss_trigger': f"单股亏损达到{self.investment_config['max_single_loss']*100}%",
                'portfolio_stop_loss': f"总体亏损达到{self.investment_config['max_total_loss']*100}%",
                'rebalance_threshold': self.investment_config['rebalance_threshold'],
                'avg_risk_level': total_risk_score / len(selected_stocks)
            }
            
            print("🔄 设置时间计划...")
            # 时间计划
            trading_plan['timeline'] = {
                'start_date': datetime.now().strftime('%Y-%m-%d'),
                'target_hold_period': '5-7个交易日',
                'daily_review_time': '15:30',
                'weekly_rebalance_day': '周五',
                'monthly_review_date': '月末'
            }
            
            # 预期收益
            trading_plan['expected_portfolio_return'] = total_expected_return
            
            print("✅ 交易计划生成完成")
            return trading_plan
            
        except Exception as e:
            print(f"❌ 生成交易计划失败: {e}")
            import traceback
            traceback.print_exc()
            return {}
    
    def generate_risk_management_plan(self, trading_plan):
        """生成风险管理计划"""
        try:
            risk_plan = {
                'position_limits': {
                    'max_single_position': 25,  # 单只股票最大仓位25%
                    'max_sector_exposure': 40,  # 单行业最大敞口40%
                    'min_diversification': 3,   # 最少分散化股票数
                },
                'stop_loss_rules': {
                    'individual_stop_loss': f"{self.investment_config['max_single_loss']*100}%",
                    'portfolio_stop_loss': f"{self.investment_config['max_total_loss']*100}%",
                    'trailing_stop': '2%',
                    'time_stop': '2周无盈利'
                },
                'take_profit_rules': {
                    'target_profit': f"{self.investment_config['weekly_target_return']*100}%",
                    'partial_profit_taking': '盈利2%时减半仓位',
                    'full_profit_taking': '盈利3%时全部止盈'
                },
                'monitoring_alerts': {
                    'price_alerts': '价格变动超过2%',
                    'volume_alerts': '成交量异常放大',
                    'news_alerts': '重大消息面影响',
                    'technical_alerts': '技术指标背离'
                },
                'emergency_procedures': {
                    'market_crash': '大盘下跌超过5%时全部止损',
                    'individual_stock_risk': '个股出现重大利空立即止损',
                    'system_failure': '系统故障时的应急操作流程',
                    'liquidity_crisis': '流动性不足时的处理方案'
                }
            }
            
            # 基于投资组合特征调整风险参数
            if trading_plan and 'stocks' in trading_plan:
                avg_confidence = np.mean([stock['confidence'] for stock in trading_plan['stocks']])
                
                if avg_confidence < 0.6:
                    risk_plan['position_limits']['max_single_position'] = 20
                    risk_plan['stop_loss_rules']['individual_stop_loss'] = '2.5%'
                    print("⚠️ 低置信度组合，收紧风险控制")
                
            return risk_plan
            
        except Exception as e:
            print(f"❌ 生成风险管理计划失败: {e}")
            return {}
    
    def generate_monitoring_schedule(self, trading_plan):
        """生成监控计划"""
        try:
            monitoring_schedule = {
                'daily_tasks': {
                    '09:00': '查看盘前消息和公告',
                    '09:25': '观察集合竞价情况',
                    '10:00': '检查开盘后股价表现',
                    '11:30': '上午盘中期评估',
                    '13:30': '下午开盘后检查',
                    '15:00': '收盘前最后检查',
                    '15:30': '收盘后数据更新和分析',
                    '21:00': '晚间复盘和计划调整'
                },
                'weekly_tasks': {
                    '周一': '制定本周交易计划',
                    '周三': '中期评估和调整',
                    '周五': '周总结和下周规划',
                    '周末': '深度分析和系统优化'
                },
                'monthly_tasks': {
                    '月初': '制定月度投资策略',
                    '月中': '中期业绩评估',
                    '月末': '月度总结和策略调整'
                },
                'key_indicators': {
                    'performance_metrics': ['收益率', '夏普比率', '最大回撤', '胜率'],
                    'risk_metrics': ['VaR', '波动率', '贝塔系数', '相关性'],
                    'trading_metrics': ['换手率', '交易成本', '执行偏差', '时机把握']
                },
                'alert_conditions': {
                    'immediate_alerts': [
                        '个股跌幅超过3%',
                        '组合跌幅超过2%',
                        '异常交易量',
                        '重大消息公告'
                    ],
                    'daily_alerts': [
                        '技术指标突破',
                        '基本面数据更新',
                        '行业板块异动',
                        '宏观经济数据'
                    ]
                }
            }
            
            return monitoring_schedule
            
        except Exception as e:
            print(f"❌ 生成监控计划失败: {e}")
            return {}
    
    def generate_comprehensive_report(self, trading_plan, risk_plan, monitoring_schedule):
        """生成综合投资报告"""
        try:
            report = f"""# 🚀 A股量化投资系统 - 完整投资方案

## 📊 投资概况
- **分析时间**: {datetime.now().strftime('%Y年%m月%d日 %H:%M:%S')}
- **投资资金**: ¥{self.investment_config['total_capital']:,}
- **投资标的**: {len(trading_plan['stocks'])}只优质股票
- **投资目标**: 周收益{self.investment_config['weekly_target_return']*100}%
- **风险控制**: 最大亏损{self.investment_config['max_total_loss']*100}%

## 🎯 投资组合配置

### 股票明细
"""
            
            total_allocation = 0
            for i, stock in enumerate(trading_plan['stocks'], 1):
                allocation = stock['allocation']
                total_allocation += allocation
                
                report += f"""
#### {i}. {stock['code']} - {stock['name']}
- **配置金额**: ¥{allocation:,.0f} ({stock['allocation_percentage']:.1f}%)
- **当前价格**: ¥{stock['current_price']:.2f}
- **目标价格**: ¥{stock['target_price']:.2f}
- **止损价格**: ¥{stock['stop_loss_price']:.2f}
- **止盈价格**: ¥{stock['take_profit_price']:.2f}
- **预期收益**: {stock['expected_return']:.2f}%
- **风险等级**: {stock['risk_level']}
- **置信度**: {stock['confidence']:.1%}
- **建议股数**: {stock['shares_to_buy']}股
- **操作建议**: {stock['operation_advice']}
"""
            
            report += f"""

### 投资组合统计
- **总配置金额**: ¥{total_allocation:,.0f}
- **资金利用率**: {total_allocation/self.investment_config['total_capital']*100:.1f}%
- **预期组合收益**: {trading_plan['expected_portfolio_return']:.2f}%
- **平均风险等级**: {risk_plan.get('avg_risk_level', 2.0):.1f}

## 📈 交易执行计划

### 买入策略
1. **分批买入**: 每只股票分2-3次买入，间隔1-2个交易日
2. **时机选择**: 开盘后30分钟内或收盘前30分钟
3. **价格控制**: 不超过前一日收盘价的2%
4. **数量控制**: 首次买入50%，后续根据表现调整

### 卖出策略
1. **止损策略**: 单股亏损达到{risk_plan['stop_loss_rules']['individual_stop_loss']}立即止损
2. **止盈策略**: 达到{risk_plan['take_profit_rules']['target_profit']}目标收益时止盈
3. **时间止损**: 持有超过2周无盈利考虑止损
4. **技术止损**: 技术指标出现明显背离时止损

## ⚠️ 风险管理

### 风险控制原则
1. **仓位控制**: 单只股票最大仓位不超过{risk_plan['position_limits']['max_single_position']}%
2. **行业分散**: 单一行业敞口不超过{risk_plan['position_limits']['max_sector_exposure']}%
3. **相关性控制**: 避免高度相关股票同时持有
4. **流动性管理**: 确保所有股票具备良好流动性

### 止损机制
- **个股止损**: {risk_plan['stop_loss_rules']['individual_stop_loss']}
- **组合止损**: {risk_plan['stop_loss_rules']['portfolio_stop_loss']}
- **追踪止损**: {risk_plan['stop_loss_rules']['trailing_stop']}
- **时间止损**: {risk_plan['stop_loss_rules']['time_stop']}

### 应急预案
- **市场崩盘**: {risk_plan['emergency_procedures']['market_crash']}
- **个股风险**: {risk_plan['emergency_procedures']['individual_stock_risk']}
- **系统故障**: {risk_plan['emergency_procedures']['system_failure']}
- **流动性危机**: {risk_plan['emergency_procedures']['liquidity_crisis']}

## 📅 监控计划

### 日常监控
"""
            
            for time_slot, task in monitoring_schedule['daily_tasks'].items():
                report += f"- **{time_slot}**: {task}\n"
            
            report += f"""

### 周度检查
"""
            for day, task in monitoring_schedule['weekly_tasks'].items():
                report += f"- **{day}**: {task}\n"
            
            report += f"""

### 关键指标监控
"""
            for category, metrics in monitoring_schedule['key_indicators'].items():
                report += f"- **{category}**: {', '.join(metrics)}\n"
            
            report += f"""

## 🎯 业绩预期

### 收益预期
- **周收益目标**: {self.investment_config['weekly_target_return']*100}%
- **月收益预期**: {self.investment_config['weekly_target_return']*4*100:.1f}%
- **年化收益预期**: {self.investment_config['weekly_target_return']*52*100:.1f}%
- **组合预期收益**: {trading_plan['expected_portfolio_return']:.2f}%

### 风险评估
- **最大回撤预期**: {self.investment_config['max_total_loss']*100}%
- **波动率估计**: 15-20%
- **胜率预期**: 70%以上
- **风险调整收益**: 夏普比率>1.5

## 🔄 动态调整机制

### 再平衡条件
1. **权重偏离**: 个股权重偏离目标超过{self.investment_config['rebalance_threshold']*100}%
2. **业绩分化**: 个股收益差异超过5%
3. **基本面变化**: 公司基本面发生重大变化
4. **技术突破**: 技术指标出现重要信号

### 调整频率
- **日常调整**: 根据盘中表现微调
- **周度调整**: 每周五收盘后评估
- **月度调整**: 每月末全面评估
- **季度调整**: 每季度战略性调整

## 📞 操作执行

### 交易时间安排
- **开盘**: 09:30-10:00 (观察开盘情况)
- **上午**: 10:00-11:30 (主要交易时段)
- **下午**: 13:30-15:00 (调整和平仓)
- **收盘**: 15:00-15:30 (数据更新)

### 操作注意事项
1. **严格执行**: 严格按照计划执行，不随意改变
2. **情绪控制**: 保持冷静，避免情绪化交易
3. **风险优先**: 风险控制优先于收益追求
4. **持续学习**: 不断优化和改进策略

## 📊 系统优势

### 科学性
- **数据驱动**: 基于大量历史数据和实时分析
- **模型优化**: 多模型集成，提高预测准确性
- **风险量化**: 完整的风险评估和控制体系

### 实用性
- **操作具体**: 详细的操作指南和时间安排
- **风险可控**: 完善的风险管理机制
- **收益可期**: 合理的收益预期和实现路径

### 适应性
- **动态调整**: 根据市场变化及时调整策略
- **持续优化**: 不断学习和改进系统
- **灵活执行**: 根据实际情况灵活调整操作

---

## ⚠️ 重要提示

1. **投资有风险，入市需谨慎**
2. **本报告基于历史数据和模型分析，不构成投资建议**
3. **实际操作中请结合市场情况和个人风险承受能力**
4. **建议在专业人士指导下进行投资操作**
5. **请严格执行风险控制措施，保护投资本金**

---

*报告生成时间: {datetime.now().strftime('%Y年%m月%d日 %H:%M:%S')}*
*系统版本: A股量化投资系统 v1.0*
*有效期: 1周 (建议每周更新)*
"""
            
            return report
            
        except Exception as e:
            print(f"❌ 生成综合报告失败: {e}")
            return ""
    
    def generate_investment_advice(self):
        """生成完整的投资建议"""
        try:
            print("🔄 开始生成完整投资建议...")
            
            # 1. 加载所有分析结果
            print("\n📊 第1步: 加载分析结果")
            all_results = self.load_all_analysis_results()
            
            if not all_results:
                print("❌ 没有可用的分析结果")
                return None
            
            # 2. 选择最终投资组合
            print("\n🎯 第2步: 选择投资组合")
            selected_stocks = self.select_final_portfolio(all_results)
            
            if not selected_stocks:
                print("❌ 无法选择投资组合")
                return None
            
            # 3. 计算仓位配置
            print("\n💰 第3步: 计算仓位配置")
            selected_stocks = self.calculate_position_sizing(selected_stocks)
            
            # 4. 生成交易计划
            print("\n📋 第4步: 生成交易计划")
            trading_plan = self.generate_trading_plan(selected_stocks)
            
            # 5. 生成风险管理计划
            print("\n⚠️ 第5步: 生成风险管理计划")
            risk_plan = self.generate_risk_management_plan(trading_plan)
            
            # 6. 生成监控计划
            print("\n📅 第6步: 生成监控计划")
            monitoring_schedule = self.generate_monitoring_schedule(trading_plan)
            
            # 7. 生成综合报告
            print("\n📝 第7步: 生成综合报告")
            comprehensive_report = self.generate_comprehensive_report(trading_plan, risk_plan, monitoring_schedule)
            
            return {
                'trading_plan': trading_plan,
                'risk_plan': risk_plan,
                'monitoring_schedule': monitoring_schedule,
                'comprehensive_report': comprehensive_report,
                'selected_stocks': selected_stocks
            }
            
        except Exception as e:
            print(f"❌ 生成投资建议失败: {e}")
            return None
    
    def save_investment_plan(self, investment_advice, filename_prefix="final_investment_plan"):
        """保存投资计划"""
        try:
            if not investment_advice:
                return False
            
            # 保存交易计划到CSV
            if 'trading_plan' in investment_advice and 'stocks' in investment_advice['trading_plan']:
                trading_df = pd.DataFrame(investment_advice['trading_plan']['stocks'])
                trading_csv = f"{filename_prefix}_trading_plan.csv"
                trading_df.to_csv(trading_csv, index=False, encoding='utf-8')
                print(f"✅ 交易计划已保存: {trading_csv}")
            
            # 保存综合报告到Markdown
            if 'comprehensive_report' in investment_advice:
                report_md = f"{filename_prefix}_comprehensive_report.md"
                with open(report_md, 'w', encoding='utf-8') as f:
                    f.write(investment_advice['comprehensive_report'])
                print(f"✅ 综合报告已保存: {report_md}")
            
            return True
            
        except Exception as e:
            print(f"❌ 保存投资计划失败: {e}")
            return False

if __name__ == "__main__":
    # 简单测试
    advisor = OptimizedInvestmentAdvisor()
    print("✅ 优化投资建议系统初始化成功")
